package com.hzdl.cinema.web.servlet;

import com.hzdl.cinema.Service.StudioService;
import com.hzdl.cinema.Service.impl.StudioServiceImpl;
import com.hzdl.cinema.domain.Studio;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/studio/*")
public class StudioServlet extends BaseServlet {
    StudioService studioService = new StudioServiceImpl();

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Studio> studioList=studioService.findAll();
        writeValue(response,studioList);
    }

    public void findStudioById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int studioId = Integer.parseInt(request.getParameter("studioId"));
        Studio studio=studioService.findStudioById(studioId);
        writeValue(response,studio);
    }

    public void addStudio(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Studio studio=new Studio();
        try {
            BeanUtils.populate(studio,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        boolean flag=studioService.addStudio(studio);
        writeValue(response,flag);
    }

    public void editStudio(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int studioId = Integer.parseInt(request.getParameter("studioId"));
        Map<String, String[]> parameterMap = request.getParameterMap();
        Studio studio=new Studio();
        try {
            BeanUtils.populate(studio,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        studioService.editStudio(studioId,studio);
    }

    public void deleteStudioById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int studioId = Integer.parseInt(request.getParameter("studioId"));
        studioService.deleteStudioById(studioId);
    }

    public void searchStudioByName(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        request.setCharacterEncoding("utf-8");
        String studioName = request.getParameter("studioName");
        studioName= new String(studioName.getBytes("ISO8859_1"), "utf-8");
        Studio studio=studioService.searchStudioByName(studioName);
        writeValue(response,studio);
    }

}
